/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import model.Device;

/**
 *
 * @author modesto
 */
public class DeviceDAO extends DAO {
    
    public DeviceDAO() throws ClassNotFoundException, SQLException {
        super();
    }
    
    public void add(Device d) throws SQLException {
        String sql = "INSERT INTO device VALUES (NULL, ?, INET_ATON(?), ?, ?, ?)";
        
        PreparedStatement stmt = this.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        
        stmt.setString(1, d.getHostname());
        stmt.setString(2, d.getIp());
        stmt.setInt(3, d.getSshPort());
        stmt.setBoolean(4, d.isZebraEnabled());
        stmt.setBoolean(5, d.isBgpdEnabled());
        
        stmt.executeUpdate();
        
        ResultSet rs = stmt.getGeneratedKeys();
        
        rs.first();
        
        d.setId(rs.getInt(1));
        
    }
    
    
    public int remove(Device d) throws SQLException {
        String sql = "DELETE FROM device WHERE id = ?";
        
        PreparedStatement stmt = this.getConnection().prepareStatement(sql);
        
        stmt.setInt(1, d.getId());
        
        return stmt.executeUpdate();
    }
    
    
    public int update(Device d) throws SQLException {
        String sql = "UPDATE device set hostname = ?, "
                + "ip = INET_ATON(?), "
                + "sshport = ?, "
                + "zebra = ?, "
                + "bgpd = ? WHERE id = ?";
        
        PreparedStatement stmt = this.getConnection().prepareStatement(sql);
        
        stmt.setString(1, d.getHostname());
        stmt.setString(2, d.getIp());
        stmt.setInt(3, d.getSshPort());
        stmt.setBoolean(4, d.isZebraEnabled());
        stmt.setBoolean(5, d.isBgpdEnabled());
        stmt.setInt(6, d.getId());
        
        return stmt.executeUpdate();
    }
    
    
    public ArrayList<Device> getAll() throws SQLException {
        ArrayList<Device> deviceList = new ArrayList<>();
        String sql = "SELECT id, hostname, INET_NTOA(ip) as ip, sshport, zebra, bgpd FROM device";
        
        PreparedStatement stmt = this.getConnection().prepareStatement(sql);
        
        ResultSet rs = stmt.executeQuery();
        
        while (rs.next()) {
            Device d = new Device();
            d.setId(rs.getInt("id"));
            d.setHostname(rs.getString("hostname"));
            d.setIp(rs.getString("ip"));
            d.setSshPort(rs.getInt("sshport"));
            d.setZebraEnabled(rs.getBoolean("zebra"));
            d.setBgpdEnabled(rs.getBoolean("bgpd"));
            
            deviceList.add(d);
        }
        
        return deviceList;
    }
    
}
